package com.zyf.chapter02.creation.prototype;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 替换数据为最新版本，目前仅仅存在增加和更新的需求
 *
 * @author yifeng
 */
public class V1Demo {
    private ConcurrentHashMap<String, SearchWord> currentKeywords = new ConcurrentHashMap<>();
    private long lastUpdateTime = -1;

    public void refresh() {
        // 从数据中取出更新时间 > lastUpdateTime 的数据，放入到 currentKeyword 中
        List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);
        long maxNewUpdatedTime = lastUpdateTime;
        for (SearchWord searchWord : toBeUpdatedSearchWords) {
            // 更新最新时间
            if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
                maxNewUpdatedTime = searchWord.getLastUpdateTime();
            }
            // 存在则替换
            if (currentKeywords.containsKey(searchWord.getKeyword())) {
                currentKeywords.replace(searchWord.getKeyword(), searchWord);
            // 否则就插入
            } else {
                currentKeywords.put(searchWord.getKeyword(), searchWord);
            }
        }
        lastUpdateTime = maxNewUpdatedTime;
    }

    private List<SearchWord> getSearchWords(long lastUpdateTime) {
        // 从数据库中取出更新时间 > lastUpdateTime 的数据
        return null;
    }
}
